/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.customer.api;

import net.dgg.dggcloud.core.util.NJCodeUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.BusinessConstant;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ContactDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CustomerDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.customer.*;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import net.dgg.dggcloud.service.jrcrm.service.cms.BillNumberRuleService;
import net.dgg.dggcloud.service.jrcrm.service.customer.ContactService;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import net.dgg.dggcloud.service.jrcrm.vo.CusAttrVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户管理业务处理层-对外接口
 * @ClassName: CustomerApiService
 * @Author: 周潮
 * @Date: 2017年11月03 14:34:05
 * @Version V1.0
 */

@Service
public class CustomerApiService extends BaseService{

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private ContactDao contactDao;
    @Resource
    private BillNumberRuleService bs ;
    @Resource
    private CustomerAttrApiService customerAttrApiService;
    @Resource
    private CustomerService customerService;
    @Resource
    private ContactService contactService;
    @Resource
    private BusinessAbilityService businessAbilityService;
    @Resource
    private NJCodeUtil njCodeUtil;

    public Customer getCustomerById(Long cusId){
        return repository.get(Customer.class,cusId);
    }

    /**
     * 根据客户联系方式、联系号码查询客户list
     * @param map
     * @return
     */
    public List<Map> queryCustomerListByParams(Map map){
        return customerDao.queryCustomerListByParams(map);
    }

    /**
     * 客户查重
     * @param map
     * customerNumber：客户号码<br/>
     * contactWay：联系方式（手机、座机、微信、QQ）<br/>
     * @return
     */
    public Integer queryCustomerRepeatCount(Map map){
        return contactDao.queryContactCountForJudgeRepeat(map);
    }


    /**
     * 新增客户
     * @param map 参数 <br/>
     *  name：客户名称<br/>
     *  customerNumber：客户号码<br/>
     *  contactWay：联系方式（手机、座机、微信、QQ）<br/>
     *  customerType：客户类型（个人/企业）<br/>
     *  idCard：身份证号码<br/>
     *  age：年龄<br/>
     *  sex：性别<br/>
     *  birthday：生日<br/>
     *  address：家庭住址<br/>
     *  registeredResidence：户口所在地<br/>
     *  email：邮件<br/>
     *  maritalStatus：婚姻状况<br/>
     *  eduBackground：学历<br/>
     *  customerAttr：客户属性<br/>
     *  origin：来源code<br/>
     *  originName：来源名称<br/>
     *  User：操作人<br/>
     *  business：商机<br/>
     *  contacts：联系人<br/>
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map saveCustomer(Map map){
        Map result = new HashMap();

        if(null == map.get("name")){
            throw new BizException("新增客户失败！客户名称为空！", 10005);
        }
        if(null == map.get("customerNumber")){
            throw new BizException("新增客户失败！客户联系号码为空！", 10005);
        }
        if(null == map.get("customerType")){
            throw new BizException("新增客户失败！客户类型为空！", 10005);
        }
        if(null == map.get("origin")){
            throw new BizException("新增客户失败！客户来源为空！", 10005);
        }
        if(null == map.get("originName")){
            throw new BizException("新增客户失败！客户来源为空！", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("新增客户失败！新增人信息为空！", 10005);
        }
        if(null == map.get("business")){
            throw new BizException("新增客户失败！商机信息为空！", 10005);
        }

        Map params = new HashMap();
        params.put("contactWay", map.get("contactWay"));
        params.put("customerNumber", map.get("customerNumber"));
        Integer repeatCount = contactDao.queryContactCountForJudgeRepeat(params);
        if(repeatCount >0 ){
            throw new BizException("新增客户失败！该客户号码已存在，不能重复添加客户！", 10005);
        }
        User user = (User) map.get("User");
        Business business = (Business) map.get("business");
        //保存客户
        Customer customer = new Customer();
        long cid = this.keyWorker.nextId();
        customer.setId(cid);
        String no = bs.updateBillNumberByCode("KH");
        customer.setNo(no);
        customer.setCreateUser((User)map.get("User"));//操作人
        customer.setName(map.get("name").toString());//客户名称
        customer.setCustomerType(map.get("customerType").toString());//客户类型（个人/企业）
        customer.setCustomerPhone(map.get("customerNumber").toString());//客户号码
        customer.setCustomerPhoneBak(njCodeUtil.decrypt(map.get("customerNumber").toString()));//客户号码
        customer.setLastBusId(business.getId());//商机id

        if(null == map.get("contactWay")){
            customer.setContactWay(CustomerConstant.CUS_CONTACT_WAY_MOBILE);//如果为空默认未手机
        }else{
            customer.setContactWay(map.get("contactWay").toString());//联系方式（手机、座机、微信、QQ）
        }

        customer.setIdCard((null == map.get("idCard")) ? null : map.get("idCard").toString());//身份证号码

        if(null != map.get("idCard") && StringUtils.isNotEmpty(map.get("idCard").toString())){//有身份证,自动计算年龄
            String idCard = map.get("idCard").toString();
            customer.setBirthday(calcBirthday(idCard));//生日
        }else{
            customer.setBirthday((null == map.get("birthday")) ? null : map.get("birthday").toString());//生日
        }

        customer.setAge((null == map.get("age") || StringUtils.isBlank(map.get("age").toString())) ? null : Integer.parseInt(map.get("age").toString()));//年龄
        customer.setChildrenNum((null == map.get("childrenNum") || StringUtils.isBlank(map.get("childrenNum").toString())) ? null : Integer.parseInt(map.get("childrenNum").toString()));//子女个数
        customer.setSex((null == map.get("sex")) ? null : map.get("sex").toString());//性别
        customer.setAddress((null == map.get("address")) ? null : map.get("address").toString());//家庭住址
        customer.setEmail((null == map.get("email")) ? null : map.get("email").toString());//邮箱
        customer.setRegisteredResidence((null == map.get("registeredResidence")) ? null : map.get("registeredResidence").toString());//户口所在地
        customer.setMaritalStatus((null == map.get("maritalStatus")) ? null : map.get("maritalStatus").toString());//婚姻状况
        customer.setEduBackground((null == map.get("eduBackground")) ? null : map.get("eduBackground").toString());//学历
        customer.setOrigin((null == map.get("origin")) ? null : map.get("origin").toString());//来源code
        customer.setOriginName((null == map.get("originName")) ? null : map.get("originName").toString());//来源名称
        customer.setCreateUser(user);
        String customerPhone = map.get("customerNumber").toString();
        Map attrMap = new HashMap();
        if(null==customer.getAge()) {
            attrMap.put("customerPhone", map.get("customerNumber"));
            Query query = repository.getSession().createQuery("From CustomerForm where phone ='" + customerPhone + "'");
            if (query.list().size() > 0) {
                CustomerForm cf = (CustomerForm) query.list().get(0);
                customer.setAge(cf.getAge() == null ? 0 : cf.getAge());
                ;
            }
        }
        repository.save(customer);

        //保存客户新增记录
        customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Customer.TABLE_NAME, customer.getId(), CustomerConstant.CUS_OPERATE_CUS_SAVE, user.getId(), "新增客户");

        map.put("customerId", cid);
        map.put("customer", customer);

        CusAttrVo cusAttrVo = null;
        CusAttrVo qusAttrVo = null;
        //保存客户属性
        try {

            qusAttrVo = customerAttrApiService.findCustomerAttrsByCustomerForm(attrMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if(null != map.get("customerAttr") && StringUtils.isNotBlank(map.get("customerAttr").toString()) && null != customer.getId()){
            //获取客户属性Vo
            cusAttrVo = customerAttrApiService.saveAttr(map);
        }
        if(null!=qusAttrVo){
            if(cusAttrVo==null){
                cusAttrVo = new CusAttrVo();
            }
            if(cusAttrVo.getAttrOther()==null){ //其他
                if(qusAttrVo.getAttrOther()!=null){
                    AttrOther ao = new AttrOther();
                    ao.setOther(qusAttrVo.getAttrOther().getOther());
                    ao.setAmount(qusAttrVo.getAttrOther().getAmount());
                    cusAttrVo.setAttrOther(ao);
                }
            }
            if(cusAttrVo.getAttrBuildings()==null){ //房子
                if(qusAttrVo.getAttrBuildings()!=null){
                    List <AttrBuilding> list = new ArrayList<>();
                    AttrBuilding ab = new AttrBuilding();
                    ab.setBuildingType(qusAttrVo.getAttrBuildings().get(0).getBuildingType());
                    ab.setPayType(qusAttrVo.getAttrBuildings().get(0).getPayType());
                    list.add(ab);
                    cusAttrVo.setAttrBuildings(list);
                }
            }
            if(cusAttrVo.getAttrVehicles()==null){ //车子
                if(qusAttrVo.getAttrVehicles()!=null){
                    List <AttrVehicle> list = new ArrayList<>();
                    AttrVehicle av = new AttrVehicle();
                    av.setBareCarPrice(qusAttrVo.getAttrVehicles().get(0).getBareCarPrice());
                    av.setPayType(qusAttrVo.getAttrVehicles().get(0).getPayType());
                    list.add(av);
                    cusAttrVo.setAttrVehicles(list);
                }
            }
            if(cusAttrVo.getAttrAccFund()==null){//公积金
                if(qusAttrVo.getAttrAccFund()!=null){
                    AttrAccFund af = new AttrAccFund();
                    cusAttrVo.setAttrAccFund(af);
                }
            }
            if(cusAttrVo.getAttrJob()==null){//工作
                if(qusAttrVo.getAttrJob()!=null){
                    AttrAccFund af = new AttrAccFund();
                    cusAttrVo.setAttrAccFund(af);
                }
            }
            if(cusAttrVo.getAttrCreditCard()==null){//信用卡
                if(qusAttrVo.getAttrCreditCard()!=null){
                    AttrCreditCard af = new AttrCreditCard();
                    cusAttrVo.setAttrCreditCard(af);
                }
            }

            if(cusAttrVo.getAttrLiability()==null){//负债
                if(qusAttrVo.getAttrLiability()!=null){
                    AttrLiability af = new AttrLiability();
                    cusAttrVo.setAttrLiability(af);
                }
            }

            if(cusAttrVo.getAttrPolicy()==null){//保单
                if(qusAttrVo.getAttrPolicy()!=null){
                    AttrPolicy af = new AttrPolicy();
                    cusAttrVo.setAttrPolicy(af);
                }
            }

            if(cusAttrVo.getAttrSocialSecurity()==null){//社保
                if(qusAttrVo.getAttrSocialSecurity()!=null){
                    AttrSocialSecurity af = new AttrSocialSecurity();
                    cusAttrVo.setAttrSocialSecurity(af);
                }
            }

        }
            map.put("customerAttr",cusAttrVo);
            if(cusAttrVo!=null)
            cusAttrVo = customerAttrApiService.saveAttr(map);


        if(null != map.get("contacts")){
            //联系人列表
            List<Contact> contacts = (List<Contact>) map.get("contacts");
            for (Contact contact : contacts){
                //保存联系人
                if(contact.getId() == null){
                    long tid = this.keyWorker.nextId();
                    contact.setId(tid);
                }
                contact.setCustomerId(cid);
//                contact.setRelationshipOfCus("ORF_JDRGX_1");//默认为本人
//                contact.setStatus(CustomerConstant.CUS_CONTACT_STATUS_2);//默认为主联系人
//                contact.setName(customer.getName());
//                contact.setNo(customer.getCustomerPhone());//联系号码
//                contact.setContactWay(customer.getContactWay());//联系方式（手机、座机、微信、QQ）
                contact.setCreateUser(user);
                contact.setUpdaterUser(user);

                if(null != contact.getStatus() && contact.getStatus().equals(CustomerConstant.CUS_CONTACT_STATUS_2)){
                    //保存客户上面主联系人信息
                    contactService.updateCusMainContact(contact, user, customer);
//                    customer.setMainContactId(contact.getId());
//                    customer.setMainContactNo(contact.getNo());
//                    customer.setMainContactName(contact.getName());
//                    repository.saveOrUpdate(customer);
//                    contact.setRelationshipOfCus("ORF_JDRGX_1");//默认为本人
                }else {
                    contact.setRelationshipOfCus("ORF_JDRGX_5");
                    repository.saveOrUpdate(contact);
                    //保存联系人新增记录
                    customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, user.getId(), "新增联系人");
                }

            }
        }else{
            //保存联系人
            Contact contact = new Contact();
            long tid = this.keyWorker.nextId();
            contact.setId(tid);
            contact.setCustomerId(cid);
            contact.setRelationshipOfCus("ORF_JDRGX_1");//默认为本人
            contact.setStatus(CustomerConstant.CUS_CONTACT_STATUS_2);//默认为主联系人
            contact.setName(customer.getName());
            contact.setNo(customer.getCustomerPhone());//联系号码
            contact.setNoBak(njCodeUtil.decrypt(customer.getCustomerPhone()));//联系号码
            contact.setContactWay(customer.getContactWay());//联系方式（手机、座机、微信、QQ）
            contact.setCreateUser(user);
            repository.save(contact);

            //保存客户上面主联系人信息
            customer.setMainContactId(contact.getId());
            customer.setMainContactNo(contact.getNo());
          //  customer.setMainContactNoBak(contact.getNoBak());
            customer.setMainContactName(contact.getName());
            repository.saveOrUpdate(customer);
            //保存联系人新增记录
            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, user.getId(), "新增联系人");
        }
        result.put("info", "新增客户成功！");
        result.put("data", customer);
        try {
            if(null!=cusAttrVo){
                customerAttrApiService.updateCustomerLevel(customer, business, cusAttrVo, user);
            }
        }catch (Exception e ){
            logger.error("客户评级出错" + e.getLocalizedMessage() + "");
        }
        return result;
    }

    /**
     *
     * @param customer
     * @param user
     * @param business
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map saveCustomerAttr(Customer customer,User user,Business business){
        Map map = new HashMap();
        Map attrMap = new HashMap();
        if(null==customer.getAge()) {
            attrMap.put("customerPhone", customer.getCustomerPhone());
            Query query = repository.getSession().createQuery("From CustomerForm where phone ='" + customer.getCustomerPhone() + "'");
            if (query.list().size() > 0) {
                CustomerForm cf = (CustomerForm) query.list().get(0);
                customer.setAge(cf.getAge() == null ? 0 : cf.getAge());
            }
        }
        repository.saveOrUpdate(customer);
        CusAttrVo cusAttrVo = new
                CusAttrVo();
        CusAttrVo qusAttrVo = null;
        //保存客户属性
        try {

            qusAttrVo = customerAttrApiService.findCustomerAttrsByCustomerForm(attrMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if(null!=qusAttrVo){
          //其他
                if(qusAttrVo.getAttrOther()!=null){
                    AttrOther ao = new AttrOther();
                    ao.setOther(qusAttrVo.getAttrOther().getOther());
                    ao.setAmount(qusAttrVo.getAttrOther().getAmount());
                    cusAttrVo.setAttrOther(ao);
                }

         //房子
                if(qusAttrVo.getAttrBuildings()!=null){
                    List <AttrBuilding> list = new ArrayList<>();
                    AttrBuilding ab = new AttrBuilding();
                    ab.setBuildingType(qusAttrVo.getAttrBuildings().get(0).getBuildingType());
                    ab.setPayType(qusAttrVo.getAttrBuildings().get(0).getPayType());
                    list.add(ab);
                    cusAttrVo.setAttrBuildings(list);
                }

           //车子
                if(qusAttrVo.getAttrVehicles()!=null){
                    List <AttrVehicle> list = new ArrayList<>();
                    AttrVehicle av = new AttrVehicle();
                    av.setBareCarPrice(qusAttrVo.getAttrVehicles().get(0).getBareCarPrice());
                    av.setPayType(qusAttrVo.getAttrVehicles().get(0).getPayType());
                    list.add(av);
                    cusAttrVo.setAttrVehicles(list);
                }

  //公积金
                if(qusAttrVo.getAttrAccFund()!=null){
                    AttrAccFund af = new AttrAccFund();
                    cusAttrVo.setAttrAccFund(af);
                }

         //工作
                if(qusAttrVo.getAttrJob()!=null){
                    AttrAccFund af = new AttrAccFund();
                    cusAttrVo.setAttrAccFund(af);
                }

         //信用卡
                if(qusAttrVo.getAttrCreditCard()!=null){
                    AttrCreditCard af = new AttrCreditCard();
                    cusAttrVo.setAttrCreditCard(af);
                }


        //负债
                if(qusAttrVo.getAttrLiability()!=null){
                    AttrLiability af = new AttrLiability();
                    cusAttrVo.setAttrLiability(af);
                }


          //保单
                if(qusAttrVo.getAttrPolicy()!=null){
                    AttrPolicy af = new AttrPolicy();
                    cusAttrVo.setAttrPolicy(af);
                }


        //社保
                if(qusAttrVo.getAttrSocialSecurity()!=null){
                    AttrSocialSecurity af = new AttrSocialSecurity();
                    cusAttrVo.setAttrSocialSecurity(af);
                }


        }
        map.put("customerAttr",cusAttrVo);
        map.put("customerId",customer.getId());
        map.put("User",user);
        map.put("customer",customer);
            cusAttrVo = customerAttrApiService.saveAttr(map);

        try {
            if(null!=cusAttrVo){
                customerAttrApiService.updateCustomerLevel(customer, business, cusAttrVo, user);
            }
        }catch (Exception e ){
            logger.error("客户评级出错" + e.getLocalizedMessage() + "");
        }
        return map;
    }


    /**
     *2018-09-25收集客户属性
     * @param customer
     * @param user
     * @param
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map updateCustomerAttr(Customer customer,User user,Map originMap){
        Map map = new HashMap();
        Map attrMap = new HashMap();
//        if(null==customer.getAge()) {
//            attrMap.put("customerPhone", customer.getCustomerPhone());
//            Query query = repository.getSession().createQuery("From CustomerForm where phone ='" + customer.getCustomerPhone() + "'");
//            if (query.list().size() > 0) {
//                CustomerForm cf = (CustomerForm) query.list().get(0);
//                customer.setAge(cf.getAge() == null ? 0 : cf.getAge());
//            }
//        }
//        repository.saveOrUpdate(customer);
        CusAttrVo cusAttrVo = new
                CusAttrVo();
        CusAttrVo qusAttrVo = null;
        //保存客户属性
        try {
            net.sf.json.JSONObject jsonarray = net.sf.json.JSONObject.fromObject(originMap.get("customerAttr"));

            if(jsonarray!=null) {
                qusAttrVo = customerAttrApiService.findCustomerAttrsByCustomerOrgin(jsonarray);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if(null!=qusAttrVo){
            //其他
            if(qusAttrVo.getAttrOther()!=null){
                AttrOther ao = new AttrOther();
                ao.setOther(qusAttrVo.getAttrOther().getOther());
                ao.setAmount(qusAttrVo.getAttrOther().getAmount());
                cusAttrVo.setAttrOther(ao);
            }

            //房子
            if(qusAttrVo.getAttrBuildings()!=null){
                List <AttrBuilding> list = new ArrayList<>();
                AttrBuilding ab = new AttrBuilding();
                ab.setBuildingType(qusAttrVo.getAttrBuildings().get(0).getBuildingType());
                ab.setPayType(qusAttrVo.getAttrBuildings().get(0).getPayType());
                list.add(ab);
                cusAttrVo.setAttrBuildings(list);
            }

            //车子
            if(qusAttrVo.getAttrVehicles()!=null){
                List <AttrVehicle> list = new ArrayList<>();
                AttrVehicle av = new AttrVehicle();
                av.setBareCarPrice(qusAttrVo.getAttrVehicles().get(0).getBareCarPrice());
                av.setPayType(qusAttrVo.getAttrVehicles().get(0).getPayType());
                list.add(av);
                cusAttrVo.setAttrVehicles(list);
            }

            //公积金
            if(qusAttrVo.getAttrAccFund()!=null){
                AttrAccFund af = new AttrAccFund();
                cusAttrVo.setAttrAccFund(af);
            }

            //工作
            if(qusAttrVo.getAttrJob()!=null){
                AttrAccFund af = new AttrAccFund();
                cusAttrVo.setAttrAccFund(af);
            }

            //信用卡
            if(qusAttrVo.getAttrCreditCard()!=null){
                AttrCreditCard af = new AttrCreditCard();
                cusAttrVo.setAttrCreditCard(af);
            }


            //负债
            if(qusAttrVo.getAttrLiability()!=null){
                AttrLiability af = new AttrLiability();
                cusAttrVo.setAttrLiability(af);
            }


            //保单
            if(qusAttrVo.getAttrPolicy()!=null){
                AttrPolicy af = new AttrPolicy();
                cusAttrVo.setAttrPolicy(af);
            }


            //社保
            if(qusAttrVo.getAttrSocialSecurity()!=null){
                AttrSocialSecurity af = new AttrSocialSecurity();
                cusAttrVo.setAttrSocialSecurity(af);
            }


        }
        map.put("customerAttr",cusAttrVo);
        map.put("customerId",customer.getId());
        map.put("User",user);
        map.put("customer",customer);
        cusAttrVo = customerAttrApiService.saveAttr(map);

        try {
            if(null!=cusAttrVo){
             //    customerAttrApiService.updateCustomerLevel(customer, business, cusAttrVo, user);
            }
        }catch (Exception e ){
            logger.error("客户评级出错" + e.getLocalizedMessage() + "");
        }
        return map;
    }


    /**
     * 资源端商机
     * 根据推广的资源金额设置来源渠道类型
     *
     */
    public void setBusinessOrigincodeType(Business business,Customer customer){
        if(null!=customer) {
            Map attrMap = new HashMap();
            attrMap.put("customerPhone", customer.getCustomerPhone());
            Query query = repository.getSession().createQuery("From CustomerForm where phone ='" + customer.getCustomerPhone() + "'");
            if (query.list().size() > 0) {
                CustomerForm cf = (CustomerForm) query.list().get(0);
                cf.setMoney(NumberUtils.toLong(cf.getMoney()+""));
                if(cf.getMoney()>=0&&cf.getMoney()<50000){
                    business.setOrigincodeType(BusinessConstant.BUS_ORIGIN_TYPE_4); //二类表单
                } else if(cf.getMoney()>=50000&&cf.getMoney()<200000){
                    business.setOrigincodeType(BusinessConstant.BUS_ORIGIN_TYPE_1); //三类表单
                }else if(cf.getMoney()>=200000&&cf.getMoney()<5000000){
                    business.setOrigincodeType(BusinessConstant.BUS_ORIGIN_TYPE_5); //四类表单
                }else if(cf.getMoney()>=50000&&cf.getMoney()<200000){
                    business.setOrigincodeType(BusinessConstant.BUS_ORIGIN_TYPE_3); //五类表单
                }else{
                    business.setOrigincodeType(BusinessConstant.BUS_ORIGIN_TYPE_2); //一类表单
                }
            }
        }
    }






    /**
     * 客户基础信息修改
     * @param map 参数<br/>
     *  name：客户名称<br/>
     *  customerPhone：客户号码<br/>
     *  idCard：客户身份证<br/>
     *  business：最新商机<br/>
     *  businessId：下单商机id<br/>
     *  User：操作人id<br/>
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Customer updateCustomer(Map map){
        if(null == map.get("id")){
            throw new BizException("更新客户失败！客户ID为空！", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("更新客户失败！操作人为空！", 10005);
        }
        Long id = Long.parseLong(map.get("id").toString());
        //查询出要修改的客户
        Customer customer = repository.get(Customer.class,id);
        User user = (User) map.get("User");
        if(null == customer) {
            throw new BizException("更新客户失败！客户不存在！", 10005);
        }
        customer.setUpdaterUser(user);//操作人
        if(null != map.get("name")){//客户名称
            customer.setName(map.get("name").toString());
        }
            if(null != map.get("contactWay")){//联系方式（手机、座机、微信、QQ）
                customer.setContactWay(map.get("contactWay").toString());
            }
        if(null != map.get("customerType")){//客户类型（个人/企业）
            customer.setCustomerType(map.get("customerType").toString());
        }
        if(null != map.get("birthday")){//客户生日
            customer.setBirthday(map.get("birthday").toString());
        }

        Business business = null;
        if(null != map.get("business")){//商机id
            business = (Business) map.get("business");
            customer.setLastBusId(business.getId());
            if(null != map.get("idCard") && StringUtils.isNotEmpty(map.get("idCard").toString())){
                Boolean isUpdateIdCard = true;
                //查询客户历史商机是否已签单
                List<Map> historyBusinessList = businessAbilityService.getCustomerBusinessList(customer.getId());
                if(null != historyBusinessList && historyBusinessList.size() > 0){
                    for (Map bMap: historyBusinessList) {
                        if(null != bMap.get("businessstatus") && (bMap.get("businessstatus").toString().equals(BusinessConstant.BUS_STATUS_SIGNED) ||
                                bMap.get("businessstatus").toString().equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED))){//如果有签单的商机，则不能修改客户身份证号码
                            isUpdateIdCard = false;
                        }
                    }
                }
//                if(business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_SIGNED) || business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED)){
                if(BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus()) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())){
                    isUpdateIdCard = false;
                }
                if(isUpdateIdCard){
                    customer.setIdCard(map.get("idCard").toString());//身份证
                    String idCard = map.get("idCard").toString();
                    customer.setBirthday(calcBirthday(idCard));//生日
                }
            }else {
                customer.setBirthday((null == map.get("birthday")) ? null : map.get("birthday").toString());//生日
            }
        }

        //用于下单更新客户信息
        if(map.get("businessId") != null){
            Long businessId = Long.parseLong(map.get("businessId").toString());
            if(businessId == customer.getLastBusId().longValue()){//如果传入商机id是客户最新商机，则可以修改客户身份证号码和电话号码
                if(null != map.get("customerPhone")){//客户号码
                    customer.setCustomerPhone(map.get("customerPhone").toString());
                }
                if(null != map.get("idCard") && StringUtils.isNotEmpty(map.get("idCard").toString())){//身份证号码
                    customer.setIdCard(map.get("idCard").toString());
                    String idCard = map.get("idCard").toString();
                    customer.setBirthday(calcBirthday(idCard));//生日
                }else {
                    customer.setBirthday((null == map.get("birthday")) ? null : map.get("birthday").toString());//生日
                }
            }
        }

        if(null != map.get("age") && StringUtils.isNotBlank(map.get("age").toString())){//年龄
            customer.setAge(Integer.parseInt(map.get("age").toString()));
        }
        if(null != map.get("childrenNum") && StringUtils.isNotBlank(map.get("childrenNum").toString())){//子女个数
            customer.setChildrenNum(Integer.parseInt(map.get("childrenNum").toString()));
        }
        if(null != map.get("sex")){//性别
            customer.setSex(map.get("sex").toString());
        }
        if(null != map.get("address")){//家庭住址
            customer.setAddress(map.get("address").toString());
        }
        if(null != map.get("registeredResidence")){//户口所在地
            customer.setRegisteredResidence(map.get("registeredResidence").toString());
        }
        if(null != map.get("email")){//邮箱
            customer.setEmail(map.get("email").toString());
        }
        if(null != map.get("maritalStatus")){//婚姻状况
            customer.setMaritalStatus(map.get("maritalStatus").toString());
        }
        if(null != map.get("eduBackground")){//学历
            customer.setEduBackground(map.get("eduBackground").toString());
        }
        if(null != map.get("origin")){//来源code
            customer.setOrigin(map.get("origin").toString());
        }
        if(null != map.get("originName")){//来源名称
            customer.setOriginName(map.get("originName").toString());
        }

        //联系人列表
        List<Contact> contacts = (List<Contact>) map.get("contacts");
        if (null != contacts) {
            for (Contact contact : contacts){
                if(contact.getId() == null){
                    long tid = this.keyWorker.nextId();
                    contact.setId(tid);
                    contact.setCustomerId(customer.getId());
                }else{
                    String cname  = contact.getName();
                    contact = repository.get(Contact.class,contact.getId());
                    contact.setName(cname);
                }
                contact.setUpdaterUser(user);
                if(null != contact.getStatus() && contact.getStatus().equals(CustomerConstant.CUS_CONTACT_STATUS_2)){
                    //保存客户上面主联系人信息
                    contactService.updateCusMainContact(contact, user, customer);
                }else {
                    contact.setRelationshipOfCus("ORF_JDRGX_5");
                }
                repository.saveOrUpdate(contact);
            }
        }


        repository.saveOrUpdate(customer);
        customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Customer.TABLE_NAME, customer.getId(), CustomerConstant.CUS_OPERATE_CUS_UPDATE, user.getId(), "修改客户信息");
        try {
            customerAttrApiService.updateCustomerLevel(customer, business, null, user);
        }catch (Exception e ){
            logger.error("客户评级出错" + e.getLocalizedMessage() + "");
        }
        return customer;
    }

    /**
     * 根据身份证号码计算生日
     * @param idCard
     * @return
     */
    private String calcBirthday(String idCard){
        String birthday = "";
        String yy = "";
        String MM = "";
        String dd = "";
        if(idCard.length() == 18){
            //  通过String[]的substring方法来读取信息
            yy = idCard.substring(6,10);          //出生的年份
            MM = idCard.substring(10,12);       //出生的月份
            dd = idCard.substring(12,14);         //出生的日期
            birthday = yy.concat("-").concat(MM).concat("-").concat(dd);
        }
        return birthday;
    }
}
